xquery version "1.0";

import module namespace layout="http://www.example.com/layout" at "xmldb:exist:///db/projdb/modules/layout.xqm";
import module namespace request="http://exist-db.org/xquery/request";

declare namespace pm = "http://www.politicalmashup.nl";
declare option exist:serialize "doctype-public=-//W3C//DTD&#160;XHTML&#160;1.1//EN
                                doctype-system=http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd";
                       
declare variable $individualID {xs:string(request:get-parameter("id", ()))};
declare variable $individualTupel {doc('/db/projdb/participatie_parameters_ge2009.xml')/result/tupel[@ref=$individualID]};
declare variable $individualName {data($individualTupel/speaker)};
declare variable $individualRole {if (data($individualTupel/role)='mp') then 'Volksvertegenwoordiger' else if(data($individualTupel/role)='government') then 'Regeeringslid' else if(data($individualTupel/role)='chair') then 'Voorzitter' else 'Volksvertegenwoordiger'};
declare variable $individualSex {if (data($individualTupel/sex)= 'M') then 'Man' else if(data($individualTupel/sex) ='F') then 'Vrouw' else '-'};
declare variable $individualParty {data($individualTupel/pparty) };
declare variable $individualMayorOrNot {if(data($individualTupel/mayor) = 'TRUE') then 'Burgemeester' else 'Niet-burgemeester'};
declare variable $individualInteruptions {data($individualTupel/interuptions)};
declare variable $individualPresent {data($individualTupel/present)};
declare variable $individualParticipatedTopics {data($individualTupel/participatedTopics)};
declare variable $individualInitiatedTopics {data($individualTupel/initiatedTopics)};
declare variable $individualInitiatedParticipatedTopics {data($individualTupel/initiatedParticipatedTopics)};
declare variable $individualAvgNumberOfWords {round(data($individualTupel/avgNumberOfWords))};
declare variable $numberOfMeetings {data(doc('/db/projdb/participatie_parameters_ge2009.xml')/result/stats/numberOfMeetings)};            



 declare variable  $onderbrekersd {document('/db/projdb/onderbrekersdata.xml')/onderbrekersdata/entry};
 declare variable $onderbrentries {$onderbrekersd[data(./onderbreker) = $individualName]};
 declare variable $onderbrokeneentries {$onderbrekersd[data(./onderbrokene) = $individualName]};
 declare variable $percpersoon {local:percperpersoon($onderbrentries)};
 declare variable $perconderbrokene { local:peronderbrokene($onderbrokeneentries)  };                 
 declare variable $perpartij {local:perpartij($onderbrentries)  }; 
 declare variable $perpartijomg { local:perpartijomg($onderbrokeneentries)};
 declare variable $partijen {document('/db/projdb/partijen.xml')/partijen};
 
 declare variable $onderbreektWieNaam{<ul> {for $j in $percpersoon/entry/naam return <li><a href="{concat('individual.xql?id=',local:getId(data($j)))}">{data($j)}</a></li>}</ul>};
 
 declare variable $onderbreektWiePerc{<ul>{for $j in  $percpersoon/entry/perc return <li>{data($j)}</li>} </ul>};
 declare variable $onderbreektWieData{<ul>{for $j in $percpersoon/entry/naam return <li><a href="intdata.xql?onderbrekerID={$individualID}&amp;onderbrokeneID={local:getId(data($j))}">data</a></li>}</ul>};
 declare variable $onderbreektWieAantal{<ul>{for $j in $percpersoon/entry/aantal return <li>{data($j)}</li> }</ul>};
 declare variable $onderbreektWieGraf{<img border="1" src="https://chart.googleapis.com/chart?chs=698x250&amp;chd=t:{ string-join(for $j in $percpersoon/entry/perc
                                                                                                where $j >= 1 return $j,",") }&amp;cht=p&amp;chl={string-join(for $j in $percpersoon/entry
                                                                                                where $j/perc >= 1 return replace($j/naam,'&amp;','%26'),"|")}"/>};
declare variable $wieOnderbreektNaam{<ul>{for $j in $perconderbrokene/entry/naam return <li><a href="{concat('individual.xql?id=',local:getId(data($j)))}">{data($j)}</a></li>}</ul>};
declare variable $wieOnderbreektData{<ul>{for $j in $perconderbrokene/entry/naam return <li><a href="intdata.xql?onderbrekerID={local:getId(data($j))}&amp;onderbrokeneID={$individualID}">data</a></li>}</ul>};
declare variable $wieOnderbreektPerc{<ul>{ for $j in  $perconderbrokene/entry/perc return <li>{data($j)}</li>}</ul>};
declare variable $wieOnderbreektAantal{<ul>{for $j in $perconderbrokene/entry/aantal return <li>{data($j)}</li>}</ul>};
declare variable $wieOnderbreektGraf{<img border="1" src="https://chart.googleapis.com/chart?chs=698x250&amp;chd=t:{ string-join(for $j in $perconderbrokene/entry/perc
                                                                                                where $j >= 1 return $j,",") }&amp;cht=p&amp;chl={string-join(for $j in $perconderbrokene/entry
                                                                                                where $j/perc >= 1 return replace($j/naam,'&amp;','%26'),"|")}"/>};
                                                                                                
declare variable $onderbreektPartijNaam{<ul>{for $j in $perpartij/entry/naam return <li><a href="party.xql?id={util:string-to-binary(xs:string(data($j)))}">{data($j)}</a></li>}</ul>};
declare variable $onderbreektPartijPerc{<ul>{for $j in  $perpartij/entry/perc return <li>{data($j)}</li>}</ul>};
declare variable $onderbreektPartijAantal{<ul>{for $j in $perpartij/entry/aantal return <li>{data($j)}</li> }</ul>};
declare variable $onderbreektPartijGraf{<img border="1" src="https://chart.googleapis.com/chart?chs=698x200&amp;chco={string-join(for $j in $perpartij/entry/naam
                                                                                                             return $partijen/entry[./naam =  $j]/kleur,"|")}&amp;chd=t:{ string-join(for $j in $perpartij/entry/perc
                                                                                                return $j,",") }&amp;cht=p&amp;chl={string-join(for $j in $perpartij/entry/naam
                                                                                                return replace($j,'&amp;','%26'),"|")}"/>};
declare variable $partijenOnderbrekenNaam{<ul>{for $j in $perpartijomg/entry/naam return <li><a href="party.xql?id={util:string-to-binary(xs:string(data($j)))}">{data($j)}</a></li>}</ul>};
declare variable $partijenOnderbrekenPerc{<ul>{for $j in  $perpartijomg/entry/perc return <li>{data($j)}</li>}</ul>};
declare variable $partijenOnderbrekenAantal{<ul>{for $j in $perpartijomg/entry/aantal return <li>{data($j)}</li>}</ul>};
declare variable $partijenOnderbrekenGraf{<img border="1" src="https://chart.googleapis.com/chart?chs=698x200&amp;chco={string-join(for $j in $perpartijomg/entry/naam
                                                                                                             return $partijen/entry[./naam =  $j]/kleur,"|")}&amp;chd=t:{ string-join(for $j in $perpartijomg/entry/perc
                                                                                                return $j,",") }&amp;cht=p&amp;chl={string-join(for $j in $perpartijomg/entry/naam
                                                                                                return replace($j,'&amp;','%26'),"|")}"/>};
declare function local:getId($pnaam){
   data(doc('/db/projdb/participatie_parameters_ge2009.xml')/result/tupel[data(./speaker) = data($pnaam)]/@ref)
};


declare function local:percperpersoon($onderbrentries){
   let $amount := count($onderbrentries)
     return <percperpersoon> {
     for $i in distinct-values($onderbrentries/onderbrokene)
        let $j := $onderbrentries[./onderbrokene = $i]
        return <entry><naam>{$i}</naam><perc>{round-half-to-even(100 *count($j) div $amount,2)}</perc><aantal>{count($j)}</aantal></entry>
     
     }</percperpersoon>
};

declare function local:peronderbrokene($onderbrentries){
   let $amount := count($onderbrentries)
     return <percperpersoon> {
     for $i in distinct-values($onderbrentries/onderbreker)
        let $j := $onderbrentries[./onderbreker= $i]
        return <entry><naam>{$i}</naam><perc>{round-half-to-even(100 *count($j) div $amount,2)}</perc><aantal>{count($j)}</aantal></entry>
     
     }</percperpersoon>
};

declare function local:perpartij($onderbrentries){
   let $amount := count($onderbrentries)
     return <percperpersoon> {
     for $i in distinct-values($onderbrentries/ponderbrokene)
        let $j := $onderbrentries[./ponderbrokene= $i]
        return <entry><naam>{$i}</naam><perc>{round-half-to-even(100 *count($j) div $amount,2)}</perc><aantal>{count($j)}</aantal></entry>
     
     }</percperpersoon>
};
declare function local:perpartijomg($onderbrentries){
   let $amount := count($onderbrentries)
     return <percperpersoon> {
     for $i in distinct-values($onderbrentries/ponderbreker)
        let $j := $onderbrentries[./ponderbreker= $i]
        return <entry><naam>{$i}</naam><perc>{round-half-to-even(100 *count($j) div $amount,2)}</perc><aantal>{count($j)}</aantal></entry>
     
     }</percperpersoon>
};

declare function local:getTopics( $id ) as element()
{
    let $name := doc('/db/projdb/participatie_parameters_ge2009.xml')/result/tupel[@ref=$individualID]/speaker
    let $clusters := document('/db/projdb/clusterdataSortedBySpeakers.xml')/speakers/speaker[./name = $name]/clusters/cluster
    let $ampersand := "&#38;"
    
    return element ol {
        for $cluster in $clusters
            return element li {
                let $splittedLabels := tokenize( $cluster/fullLabel, ",\s" )
                for $label in $splittedLabels
                    let $topics := $cluster/label[data(./name) = data($label)]/topics
                    return
                        if ( count( $topics ) > 0 ) then (
                            <a href="showTopics.xql?id={data($id)}{$ampersand}label={data($label)}">{data($label)}</a>
                        ) else (
                            <span>{data($label)}</span>
                        )
            }
    }
};

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="nl">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Activiteit in de plenaire vergaderingen</title>
        <link rel="stylesheet" style="text/css" href="style/core_layout.css"/>
		<script type="text/javascript" src="js/jquery.js"><!-- --></script>
        <script type="text/javascript" src="https://www.google.com/jsapi"><!-- --></script>
        <script type="text/javascript" src="js/activity.js"><!-- --></script>
        <script type="text/javascript" src="js/myScripts.js"><!-- --></script>
        <script type="text/javascript">
            var individualID = "{$individualID}";
            var individualPresent = {$individualPresent};
            var numberOfMeetings = {$numberOfMeetings};
            //<![CDATA[
            google.load("visualization", "1", {packages:["corechart"]});
            google.setOnLoadCallback(function() {
                initShowHideButtons();

                activity_setUpdateFunction(function(xml) {
                    activity_loadIndividualActivityChart(xml, "individualActivityChartContainer", individualID);
                    activity_loadIndividualRankingField(xml, "individualRankingField", individualID, function(xml) {
                
                        activity_loadIndividualAnnualRanking(xml, "annualValue", "annualRanking", individualID);
                    });
                });

                activity_run();
                
                // begin: static charts
                var list = [['Aanwezigheden', 'Persoon'],
                            ['Aanwezig', individualPresent],
                            ['Niet-aanwezig', numberOfMeetings - individualPresent]];

                var data = google.visualization.arrayToDataTable(list);

                var options = {
                    title: "Aanwezigheden",
                    is3D: true,
                    colors: ['#005500', '#cccccc']
                };

                var chart = new google.visualization.PieChart(document.getElementById("presentContainer"));
                chart.draw(data, options);
                // end: static charts
            });
            //]]>
        </script>
        
        
    </head>
    <body>	
            <div class="containerBox">
        {layout:topMenu()}

        <div class="box" id="titleBox">
            <div class="margin">
                <div id="individualInfoChartContainer">
                    <h1>{$individualName}</h1>
                    <strong>{$individualRole}</strong> | <strong><a href="party.xql?id={util:string-to-binary(xs:string($individualParty))}">{$individualParty}</a></strong> | <strong><a href="sexIndex.xql">{$individualSex}</a></strong> | <strong><a href="mayorIndex.xql">{$individualMayorOrNot}</a></strong>
                </div>
            </div>
        </div>

        <div class="box" id="individualChartBox">
            <div class="margin">
                <h2 class="boxTitle">Individuele informatie</h2>
                <div class="boxContent columnContent twoColumns">
                    <div class="column" id="numberInfoContainer">
                        <div class="field leftField"><a href="ranking.xql" id="individualRankingField">?</a></div>
                        <div class="field leftField"><a href="initiatives.xql?id={$individualID}">Initiatieven: #{$individualInitiatedTopics}</a></div>
                        <div class="field leftField"><a href="initiatives-participations.xql?id={$individualID}">Init+part: #{$individualInitiatedParticipatedTopics}</a></div>
                    </div>
                    <div class="column" id="otherContainer">
                        <div class="field rightField"><a href="participations.xql?id={$individualID}">Participatie: #{$individualParticipatedTopics}</a></div>
                        <div class="field rightField">Interupties: #{$individualInteruptions}</div>
                        <div class="field rightField">Gem. # woorden: #{$individualAvgNumberOfWords}</div>
                    </div>
                    <br class="clearer" />
                    <div class="column" id="presentContainer">
                        <!-- Auto generated -->
                    </div>
                    <div class="column" id="individualActivityChartContainer">
                        <!-- Auto generated -->
                    </div>
                    <br class="clearer" />
                </div>
            </div>
        </div>

        <div class="box" id="annualActivityChartBox">
            <div class="margin">
                <h2 class="boxTitle">Activiteit doorheen de jaren</h2>
                <div class="boxDescription">
                <p>In de linkergrafiek is de activiteitsgraad van de persoon in de verschillende periodes 2009-2010, 2010-2011, ... te zien. In het rood wordt de activiteitsgraad op dat moment weergegeven. In het grijs de gemiddelde activiteitsgraad op dat moment. In het blauw de totale activiteitsgraad over de hele periode heen. Merk op dat deze totale activiteitsgraad niet wordt berekend als de som van de verschillende deel-activiteitsgraden, maar wel afzonderlijk op basis van de waarden van de verschillende gemeten parameters over de hele periode heen.</p>
                <p>In de rechtergrafiek is de ranking van de persoon te zien in de verschillende periodes. Rood is de ranking van de persoon zelf, grijs is de gemiddelde ranking op dat moment en blauw is de totale ranking van de persoon over de hele periode heen. Ook hier geldt dat de totale ranking niet is gebaseerd op een soort gemiddelde van de deel-rankings, maar wel op de totale activiteitsgraad.</p>
                </div>
                <div class="boxContent twoColumns">
                    <div class="column" id="annualValue">
                    <!-- auto generated -->
                    </div>
                    <div class="column" id="annualRanking">
                    <!-- auto generated -->
                    </div>
                    <br class="clearer" />
                </div>
            </div>
        </div>

        <div class="box" id="subjectBox">
            <div class="margin">
                <h2 class="boxTitle">Onderwerpen</h2>
                <div class="boxContent columnspace oneColumn darkBackground">
                    <div class="column activityChart firstColumn">
                        { local:getTopics( $individualID ) }
                    </div>
                    <br class="clearer"/>
                </div>
            </div>
        </div>

        <div class="box" id="onderbreektWieBox">
            <div class="margin">
                <h2 class="boxTitle">{$individualName} onderbreekt wie?</h2>
                    <div class="boxContent columnspace fourColumns lessDarkBackground">
                        <div class="column">
                        <h3 class="columnTitle">Naam</h3>
                           { $onderbreektWieNaam}
                        </div>
                        <div class="column">
                        <h3 class="columnTitle">Percentage</h3>
                           { $onderbreektWiePerc}
                        </div>
                        <div class="column">
                        <h3 class="columnTitle">Aantal</h3>
                           { $onderbreektWieAantal}
                        </div>
                        <div class="column">
                        <h3 class="columnTitle">Data</h3>
                           {$onderbreektWieData}
                        </div>
                        <br class="clearer"/>
                    </div>
                    <div class="boxContent" style="margin-top:10px">
                        {$onderbreektWieGraf}
                    </div>
                    
            </div>
       </div>
       
       <div class="box" id="wieOnderbreektBox">
            <div class="margin">
                <h2 class="boxTitle">Wie Onderbreekt {$individualName}?</h2>
                    <div class="boxContent columnspace fourColumns lessDarkBackground">
                        <div class="column">
                        <h3 class="columnTitle">Naam</h3>
                           { $wieOnderbreektNaam}
                        </div>
                        <div class="column">
                        <h3 class="columnTitle">Percentage</h3>
                           { $wieOnderbreektPerc}
                        </div>
                        <div class="column">
                        <h3 class="columnTitle">Aantal</h3>
                           { $wieOnderbreektAantal}
                        </div>
                         <div class="column">
                       <h3 class="columnTitle">Data</h3>
                           {  $wieOnderbreektData}
                        </div>
                       
                      
                        <br class="clearer"/>
                    </div>
                    <div class="boxContent" style="margin-top:10px">
                        {$wieOnderbreektGraf}
                    </div> 
            </div>
       </div>
       
       <div class="box" id="onderbreektPartijBox">
            <div class="margin">
                <h2 class="boxTitle">{$individualName} onderbreekt welke partijen?</h2>
                    <div class="boxContent columnspace threeColumns lessDarkBackground">
                        <div class="column">
                        <h3 class="columnTitle">Naam</h3>
                           { $onderbreektPartijNaam}
                        </div>
                        <div class="column">
                        <h3 class="columnTitle">Percentage</h3>
                           { $onderbreektPartijPerc}
                        </div>
                        <div class="column">
                        <h3 class="columnTitle">Aantal</h3>
                           { $onderbreektPartijAantal}
                        </div>
                       
                        <br class="clearer"/>
                    </div>
                    <div class="boxContent" style="margin-top:10px">
                        {$onderbreektPartijGraf}
                    </div> 
            </div>
       </div>
       
              <div class="box" id="partijenOderbrekenBox">
            <div class="margin">
                <h2 class="boxTitle">Welke partijen onderbreken {$individualName}?</h2>
                    <div class="boxContent columnspace threeColumns lessDarkBackground">
                        <div class="column">
                        <h3 class="columnTitle">Naam</h3>
                           { $partijenOnderbrekenNaam}
                        </div>
                        <div class="column">
                        <h3 class="columnTitle">Percentage</h3>
                           { $partijenOnderbrekenPerc}
                        </div>
                        <div class="column">
                        <h3 class="columnTitle">Aantal</h3>
                           { $partijenOnderbrekenAantal}
                        </div>
                       
                        <br class="clearer"/>
                    </div>
                    <div class="boxContent" style="margin-top:10px">
                        {$partijenOnderbrekenGraf}
                    </div> 
            </div>
       </div>
    </div>
    </body>
</html>
